package cn.interestingshop.servlet;

import cn.interestingshop.entity.Goods;
import cn.interestingshop.entity.User;
import cn.interestingshop.service.GoodsService;
import cn.interestingshop.service.UserService;
import cn.interestingshop.service.impl.GoodsServiceImpl;
import cn.interestingshop.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@WebServlet("/back/GoodsInsertServlet")
@MultipartConfig
public class GoodsInsertServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //2.获取请求参数
        String categoryLevel1Id = request.getParameter("categoryLevel1Id");
        String categoryLevel2Id = request.getParameter("categoryLevel2Id");
        String categoryLevel3Id = request.getParameter("categoryLevel3Id");
        String name = request.getParameter("name");
        Part photo = request.getPart("photo");
        String price = request.getParameter("price");
        String stock = request.getParameter("stock");
        String description = request.getParameter("description");

        //3.文件上传
        String realPath = request.getServletContext().getRealPath("files/");
        File file=new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName=getFileName2(photo);
        photo.write(realPath+"/"+fileName);

        //3.调用service进行业务处理
        GoodsService service=new GoodsServiceImpl();
        Goods goods=new Goods();
        goods.setClassifyLevel1Id(Integer.parseInt(categoryLevel1Id));
        goods.setClassifyLevel2Id(Integer.parseInt(categoryLevel2Id));
        goods.setClassifyLevel3Id(Integer.parseInt(categoryLevel3Id));
        goods.setGoodsName(name);
        goods.setFileName(fileName);
        goods.setPrice(Float.parseFloat(price));
        goods.setStock(Integer.parseInt(stock));
        goods.setGoodsDesc(description);
        int i = service.insert(goods);
        //4.分析返回结果
        if(i>0){
            response.getWriter().print("<script>alert('新增成功');location.href='../back/GoodsSelectAllServlet'</script>");
        }else{
            response.getWriter().print("<script>alert('新增失败');history.go(-1)</script>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * 获取源文件名称
     * @param part
     * @return
     */
    private String getFileName(Part part) {
        String content = part.getHeader("content-disposition");
        String[] arr = content.split(";");
        for (String str : arr) {
            if (str.trim().startsWith("filename")) {
                return str.substring(str.indexOf("=") + 2, str.length() - 1);
            }
        }
        return "";
    }

    /**
     * 产生文件名
     * @return
     */
    public String getFileName2(Part part){
        //uuid作为文件名
        String fileName= UUID.randomUUID().toString().replace("-","");
        //当前时间作为文件名
        String suffix=getSuffix(part);

        return fileName+suffix;
    }

    /**
     * 获取源文件的后缀
     * @return
     */
    public String getSuffix(Part part){
        String fileName=getFileName(part);//2.png
        return fileName.substring(fileName.lastIndexOf("."));
    }

}
